class Main extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            target: {
                name: '',
                describe: '',
                number: '',
                // time:''
            },
            list: [
            ],
            ishide: 'none',
            counts: [],
            cate: [],
            start: 0,
            pagesize: 12,
            keyword: '',
            showswitch: !0,
            pagestart: 0,
            clicknew: !1,
            id: 0,
            isshow: 1,
            imgsrc: "",
            audiosrc: "",
            musicclass: '',
            // shelf:'1',
            cid: "0",
            fileimgshow: !0,
            fileaudioshow: !0,
            ischa:!1,
        };
    }
    formatlist(list) {
        console.log(list.length, 'list.length')
        var listitem = [], { cate } = this.state, nameclass = "",wulist=[];
        if (list.length > 0) {
            list.forEach((x, i) => {
                cate.forEach((y, j) => {
                    if (y.id == x.cid) {
                        nameclass = y.name
                    }
                })
                console.log(list)
                listitem.push(
                    <tr key={i}>
                        <td>
                            <div className="tdimgbox">
                                <img className="tdimg" src={`${API_HEAD}imgs/${x.thumbpath}`} />
                                <span className="ueditor" style={{ display: x.rawData ? '' : 'none' }}>富文本</span>
                            </div>
                        </td>
                        <td className="audiotitle">{x.title}</td>
                        <td className="audiodescription">{x.description}</td>
                        <td className="nameclass tconter">{nameclass}</td>
                        <td className="views tconter">{x.views > 10000 ? `${Math.floor(x.views / 10000)}万` : x.views}</td>
                        <td className="tconter"><p style={{ display: x.src ? "none" : "" }}>无</p><audio style={{ display: x.src ? "" : "none" }} src={`${Constant.AUDIOSRC}/${x.src}`} controls="controls">Your browser does not support the audio tag.</audio></td>
                        <td className="tconter">{x.state == "ON"?'上架':'下架'}</td>
                        <td className="tconter">{x.orders}</td>
                        <td className="operatebox">
                            <div className='operate' id={"ope" + x.id}>
                                <div data-toggle="modal" data-target="#modalOne">
                                    <img src="./src/edit.png" />
                                    <p className='edit' onClick={this.todetail.bind(this, x.id)}>编辑</p>
                                </div>
                                <div>
                                    <img src={`./src/${x.state == "ON" ? "lowershelf" : "shelves"}.png`} />
                                    <p className='edit' onClick={this.setshow.bind(this, x.id, x.state)}>{x.state == "ON" ? "下架" : "上架"}</p>
                                </div>
                                <div>
                                    <img src="./src/del.png" />
                                    <p className='edit colred' onClick={this.del.bind(this, x.id)}>删除</p>
                                </div>
                            </div>
                        </td>
                    </tr>

                )
            });
        } else {
            wulist.push(
                <p className="wulist">暂无数据</p>
            )
        }
        this.setState({ listitem, list, originallist: list,wulist })
    }
    // 编辑
    todetail(e) {


        window.location.href = "./audioadd.html?id=" + e;
        // var { list, imgsrc, audiosrc, musicclass, shelf, ueditor } = this.state, item = [], that = this;
        // console.log(e, 'eeee')
        // console.log(list, 'list')
        // list.forEach(x => {
        //     if (x.id == e) {
        //         ueditor.setContent(that.replaceraw(decodeURIComponent(x.rawData)))
        //         imgsrc = `${API_HEAD}imgs/${x.thumbpath}`
        //         if (x.src) {
        //             audiosrc = `${Constant.AUDIOSRC}/${x.src}`
        //             this.setState({ audiosrc, audiostate: 'isuploadaudio' })
        //         }
        //         // shelf=x.state=="ON"?"0":"1"
        //         musicclass = x.cid
        //         // $(`input[value=${shelf}]`).prop("checked","checked");
        //         $(`input[value=${musicclass}]`).prop("checked", "checked");
        //         item = { name: x.title, describe: x.description, number: x.orders }
        //     }
        // });
        // console.log(item, 'item')
        // this.setState({ id: e, target: item, clicknew: !0, imgsrc, shelf, musicclass, fileimgshow: !1, fileaudioshow: !1, imgstate: 'isBase64' })
    }
    // 上架下架
    setshow(e, i) {
        let { start } = this.state
        audiosetstate(e, res => {
            if (res.issuccess == 1) {
                alert(`${i == "OFF" ? '上架' : '下架'}成功`)
                this.freshlist(start)
            }
        })

    }

    // 删除
    del(e) {
        this.setState({ delid: e }, () => {
            $('#myModal').modal('toggle');
        })
    }
    confirmdel() {
        let { delid, start } = this.state
        audiodel(delid, res => {
            if (res.issuccess == 1) {
                alert('删除成功')
                $('#myModal').modal('toggle');
                this.freshlist(start)
            }
        })
    }

    inputchange(prop, e) {
        // console.log(prop, 'prop')
        // console.log(e.target.value, 'eeee')
        let { target } = this.state;
        target[prop] = e.target.value
        this.setState({ target })
        // this.setState({ [prop]:e.target.value }) 
    }
    inputchangeradio(prop, e) {
        console.log(prop, 'prop')
        console.log(e.target.value, 'eeee')
        this.setState({ [prop]: e.target.value })
    }
    // 点击新建或编辑
    // getnew(start) {
    //     this.setState({ clicknew: !this.state.clicknew, id: '0' });
    // }

    add(e) {
        window.location.href = "./audioadd.html";
    }
    replaceraw(content) {
        return content.replace('rgb(', 'rgb').replace(new RegExp('rgb', 'g'), "rgb(");
    }

    // submit() {
    //     var { start, imgsrc, audiosrc, imgstate, audiostate, shelf, musicclass, cate, cid, ueditor, } = this.state, pathaudio = "", pathimg = "", _this = this, err = '',
    //         { name, describe, number } = this.state.target, html = ueditor.getContent(), that = this;
    //     // time=Number(time)
    //     number = Number(number)
    //     // console.log(number, 'number')
    //     // console.log(audiosrc, 'audiosrc')
    //     var reg = /^[0-9]{1,3}$/
    //     // if(audiostate!="isuploadaudio")err="请上传音频"
    //     if (imgstate != "isBase64") err = "请上传图片"
    //     // if(isNaN(time)||time<=0)err="请输入音频时长"
    //     if (!reg.test(number)) {
    //         err = "请输入整数"
    //     }
    //     if (number > 100 || number < 0 || number == "") err = "请输入0-100的数字"
    //     // if(!audiosrc)err="请添加音频"
    //     if (describe == "") err = "请输入描述"
    //     if (musicclass.length == 0) err = "请选择音频分类"
    //     // if(shelf.length==0) err = "请选择是否上架"
    //     if (name == "") err = "请输入名称"
    //     if (!imgsrc) err = "请添加封面"
    //     if (err.length > 0) {
    //         alert(err);
    //         return
    //     }
    //     pathimg = imgsrc.replace(`${API_HEAD}imgs/`, '')
    //     pathaudio = audiosrc.replace(`${Constant.AUDIOSRC}/`, '')

    //     var submitdata = { title: name, description: describe, src: pathaudio, thumbpath: pathimg, orders: number, cid: musicclass, rawData: that.replaceraw(encodeURIComponent(html)) }
    //     if (this.state.id > 0) submitdata['id'] = this.state.id;

    //     audioaoe(submitdata, res => {
    //         if (res.issuccess == 1) {
    //             alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
    //             _this.setState({
    //                 clicknew: !1,
    //                 // target:''
    //             })
    //             _this.freshlist(start)
    //         }
    //     })

    // }
    searchinput(e) {
        // console.log(e.target.value,'e.target.value')
        this.setState({ keyword: e.target.value })
    }
    reset() {
        this.setState({ keyword: '', showswitch: !0 });
        this.freshlist(0, 'ALL');
    }
    inputchangeall() {

    }
    componentDidMount() {
        let that = this
        // let UE = window.UE
        // let ueditor = UE.getEditor('ueditor', {
        //     autoHeightEnabled: true,
        //     autoFloatEnabled: true
        // });
        // ueditor.addListener("ready", function () {
        //     that.setState({ ueditor }, () => {
        
        //     });
        // }, 2);
        let statehtml = []
        audiocatebkgetalllist(res => {
            // audiocatempgetlist(res=>{
            if (res.issuccess == 1) {
                // console.log(res.list,'res.data')
                this.inputlist(res.list);
                statehtml.push(
                    <option value="0">请选择</option>
                )
                res.list.forEach((x, i) => {
                    statehtml.push(
                        <option key={i} value={x.id}>{x.name}
                        </option>
                    )
                })
                this.setState({ statehtml },()=>{
                    that.freshlist(0)
                })
            }
        })


    }
    freshlist(start) {
        let { pagesize, list, cid,keyword } = this.state;
        audiogetlist({ pagesize, start, cid,keyword }, res => {
            if (res.issuccess == 1) {
                if (start == 0) {
                    let pagecount = Math.ceil(res.total / pagesize);
                    this.setpager(pagecount, start);
                    this.setState({ start, total: res.total })
                }
                this.formatlist(res.list);
            }
        })
        // this.formatlist(list);

    }
    inputlist(list) {
        var inputhtml = []
        list.forEach((x, i) => {
            inputhtml.push(
                <div key={i} className="radio"><input type="radio" name="radio" value={x.id} id="setmeal0" /><label for="setmeal0"></label><span>{x.name}</span></div>
            )
        })
        this.setState({ inputhtml, cate: list })
    }

    // 预览图片
    filechangeimg(e) {
        // this.setState({
        //     fileimgshow:!1,
        //     // uploadword: "上传",
        //     imgstate:''
        // })  
        var that = this;
        // var filedata = $('#file3')[0].files[0];
        var filedata = $('#file3')[0].files[0];
        let _name, _fileName;
        _name = $('#file3')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            this.setState({
                fileimgshow: !1,
                // uploadword: "上传",
                imgstate: ''
            })
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str])
            }
        }
    }
    putswiperimglistdata(target) {


        let { imgsrc } = this.state;
        imgsrc = target[0]
        if (!isBase64(imgsrc)) {
            if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                imgsrc = `${API_HEAD}imgs/${src}`

            }
        }
        this.setState({
            imgsrc
        })

    }
    // 试听音频
    filechangeaudio(e) {
        let fileaudio = $('#file0')[0].files[0];
        let _name, _fileName;
        console.log(fileaudio, 'fileaudio');
        if (fileaudio.size > 1024 * 60 * 1000) {
            alert('音频不能超过60M')
            return;
        }

        _name = $('#file0')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "mp3" && _fileName !== "wma" && _fileName !== "MP1" && _fileName !== "MP2" && _fileName !== "MPEG") {
            alert("上传音频格式不正确，请重新上传");
        } else {
            this.setState({
                // uploadword: "上传",
                fileaudio,
                audiostate: ''
            })
        }
    }

    clickupload(e) {
        $('#file' + e).click();
    }
    del_img(e) {
        console.log(e, 'eeeeeeee')
        if (e == 3) {
            this.setState({
                imgsrc: '',
                fileimgshow: !0,
                imgstate: ''
            })
        } else if (e == 0) {
            this.setState({
                audiosrc: '',
                fileaudioshow: !0,
                audiostate: ''
            })
        }
    }
    // 上传图片
    uploadimg(e) {
        let { imgsrc, imgstate } = this.state;
        if ((imgstate == "isBase64")) {
            return;
        }
        if (imgsrc) {
            if (isBase64(imgsrc)) {
                uploadimg(imgsrc, res => {
                    if (res.issuccess == 1) {
                        imgsrc = `${API_HEAD}imgs/${res.path}`
                        // imghtml.push(
                        //     <div className="img_warp">
                        //         <img src={imgsrc} className="img" />
                        //         <img className='closeimg' onClick={this.del_img.bind(this,e)} src='./src/img_close.png' />
                        //     </div>
                        // )
                        this.setState({ fileimgshow: !1, imgsrc, imgstate: 'isBase64' })
                    } else {
                        alert(res.msg)
                        err = 1
                        return;
                    }
                })
            }

        }

    }
    setpage(e) {
        let { pagesize, state, start,ischa } = this.state
        pagesize = parseInt(e)
        start = 0
        this.setState({ pagesize, start }, () => {
            this.freshlist(start, state)
        })
    }
    setpager(pagecount, start) {
        let counts = [];
        for (let i = 1; i < pagecount + 1; i++) {
            counts.push(start + i)
        }
        this.setState({ counts })
    }
    clickpage(e) {
        console.log(e)
        let { start, pagesize } = this.state
        start = e * pagesize
        this.setState({ pagestart: e, start }, () => {
            this.freshlist(start)
        })
    }


    onstatechange(e) {
        let { cid } = this.state, estate = e.target.value;
        console.log(cid, 'cid');
        console.log(e.target.value, 'e.target.value');

        if (cid == estate) return;
        this.setState({ start: 0, cid: estate }, () => {
            this.freshlist(0)
        })
    }
    // 上传音频
    uploadaudio(e) {
        let { audiosrc, fileaudio, audiostate } = this.state;
        if (audiostate == 'isuploadaudio') {
            return;
        }

        if (fileaudio) {
            uploadaudio(fileaudio, res => {
                console.log(res, 'res');
                if (res.success == 1) {
                    audiosrc = `${Constant.AUDIOSRC}/${res.path}`
                    // audiohtml.push(
                    //     <div className="audio_warp">
                    //         <audio src={audiosrc} controls="controls" id="audio">Your browser does not support the audio tag.</audio>
                    //         <button className="delaudio" onClick={this.del_img.bind(this,e)}>删除</button>
                    //     </div>
                    // )
                    this.setState({ fileaudioshow: !1, audiosrc, audiostate: 'isuploadaudio' })

                } else {
                    alert(res.msg)
                    err = 1
                    return;
                }
            })
        }
    }
    onstatechange(e) {
        let { cid } = this.state, estate = e.target.value;
        console.log(cid, 'cid');
        console.log(e.target.value, 'e.target.value');

        if (cid == estate) return;
        this.setState({ start: 0, cid: estate }, () => {
            this.freshlist(0)
        })
    }
    inputschange(e) {
        // console.log(e.target.value)
        // var txt = e.target.value;
        this.setState({
            keyword: e.target.value
        })
    }
    reset() {
        this.setState({ keyword: '' },()=>{
            this.freshlist(0);
        });
    }
    cha() {
        this.freshlist(0);
        // var { keyword, pagesize,  } = this.state;
        // var keyword = keyword
        // audiosearch(keyword, res => {
        //    if(res.issuccess==1){
        //     if (res.list) {
        //         if (start == 0) {
        //             let pagecount = Math.ceil(res.total / pagesize);
        //             this.setpager(pagecount, start);
        //             this.setState({ start, total: res.total,ischa:!0 })
        //         }
        //         this.formatlist(res.list);
        //         // this.setState({showswitch:!1})
        //     }
        //    }
        // })
    }
    render() {
        let { clicknew, counts, listitem, pagestart, keyword, showswitch, target, inputhtml, imgsrc, audiosrc,wulist } = this.state;

        return (
            <div className="breadLinebox">
                <Modal content='确定要删除吗？' click={this.confirmdel.bind(this)} />

                <div className="content_wrap panel-default content_wrap">
                    <div className='breadLine '>
                        当前位置 > 音频分类管理
                     </div>

                    <div className="content">
                        <div className="tabletit" >
                            <p className="add" data-toggle="modal" data-target="#modalOne" onClick={this.add.bind(this)}>新建</p>

                        </div>
                        <div className='choose'>
                            <p className="choose-text">选择状态:</p>
                            <select value={this.state.cid} onChange={this.onstatechange.bind(this)} className="form-control select">
                                {this.state.statehtml}
                            </select>
                        </div>


                        <div className="search">
                            <input onChange={this.inputschange.bind(this)} value={keyword} type="text" placeholder='请输入音频名称' />
                            <p className="add" onClick={this.cha.bind(this)}>查询</p>
                            <p className="add" onClick={this.reset.bind(this)}>返回</p>
                        </div>
                        <table className="tab">
                            <thead>
                                <tr>
                                    <th>封面</th>
                                    <th>名称</th>
                                    <th>描述</th>
                                    <th className="tconter">音频分类</th>
                                    <th className="tconter">浏览量</th>
                                    <th className="tconter">音频</th>
                                    <th className="tconter">状态</th>
                                    <th className="tconter">排序</th>
                                    <th className="cz tconter">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {listitem}
                            </tbody>
                        </table>
                        {wulist}
                    </div>
                    <div className="pagerbox">
                        <p>共{this.state.total}条</p>
                        <Pager counts={counts} click={this.clickpage.bind(this)} change={this.setpage.bind(this)} index={pagestart} />
                    </div>
                </div>
            </div>

        )


    }
}









ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='audiofrequency' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)
